<template>
  <!-- 列表 -->
  <ContentWrap class="full-height">
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #operate="{ row }">
        <el-button
          type="primary"
          size="small"
          @click="openForm('update', row.id)"
          v-hasPermi="['base:mail-template:update']"
          plain
          >编辑
        </el-button>
        <el-button
          type="danger"
          size="small"
          @click="handleDelete(row.id)"
          v-hasPermi="['base:mail-template:delete']"
          plain
          >删除
        </el-button>
      </template>
    </vxe-grid>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MailTemplateForm ref="formRef" @success="getList" />

  <!-- 搜索抽屉 -->
  <SearchDrawer ref="searchRef" v-model="queryParams" @search="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { MailTemplateApi, MailTemplateVO } from '@/api/base/mailtemplate'
import MailTemplateForm from './MailTemplateForm.vue'
import type { VxeGridProps, VxeGridListeners, VxeGridInstance } from 'vxe-table'
import SearchDrawer from './SearchDrawer.vue'

defineOptions({ name: 'MailTemplate' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  accountId: undefined,
  nickname: undefined,
  title: undefined,
  content: undefined,
  params: undefined,
  status: undefined,
  remark: undefined,
  createTime: []
})

const searchRef = ref()
// 表格实例
const gridRef = ref<VxeGridInstance>()

// 调用vxe grid query方法重载表格
const getList = () => {
  if (gridRef.value) {
    gridRef.value.commitProxy('query') // 触发表格重新加载数据
  }
}
// 获取表格数据
const fetchApi = () => {
  return new Promise(async (resolve) => {
    const res = await MailTemplateApi.getMailTemplatePage(queryParams)
    gridOptions.data = res.list
    resolve({
      page: {
        total: res.total
      },
      result: res.list
    })
  })
}

// 模拟后台接口
const delApi = (removeRecords: MailTemplateVO[]) => {
  return new Promise(async (resolve, reject) => {
    try {
      let ids = removeRecords.map((item) => item.id).join(',')
      await MailTemplateApi.deleteMailTemplates(ids)
      setTimeout(() => {
        resolve({
          result: [],
          msg: `delete，${removeRecords.length}条`
        })
      }, 100)
    } catch (e) {
      reject(e)
    }
  })
}

const gridOptions = reactive<VxeGridProps<MailTemplateVO>>({
  stripe: true,
  border: true,
  keepSource: true,
  height: '100%',
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },
  toolbarConfig: {
    import: false,
    export: false,
    print: false,
    zoom: true,
    custom: true,
    // slots: {
    //   buttons: 'toolbar_buttons'
    // },
    tools: [
      { name: '新增', code: 'add', status: 'primary' },
      { name: '删除', code: 'del', status: 'error' },
      { name: '', code: 'search', icon: 'vxe-icon-search', status: 'info' }
    ]
  },
  proxyConfig: {
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      // 接收 Promise
      query: ({ page }) => {
        queryParams.pageNo = page.currentPage
        queryParams.pageSize = page.pageSize
        return fetchApi()
      },
      // body 对象： { removeRecords }
      delete: ({ body }) => {
        return delApi(body.removeRecords)
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 50 },
    { type: 'seq', width: 70 },
    { field: 'code', title: '模板编码', minWidth: '100px' },
    { field: 'name', title: '模板名称', minWidth: '100px' },
    { field: 'title', title: '模板标题', minWidth: '100px' },
    { field: 'content', title: '模板内容', minWidth: '100px' },
    { field: 'accountId', title: '邮箱账号', minWidth: '100px' },
    { field: 'nickname', title: '发送人名称', minWidth: '100px' },
    { field: 'status', title: '开启状态', minWidth: '100px' },
    { field: 'createTime', title: '创建时间', minWidth: '100px' },
    { title: '操作', width: 200, slots: { default: 'operate' } }
  ],
  data: []
})

const gridEvents: VxeGridListeners = {
  toolbarButtonClick(params) {
    console.log(params.code)
  },

  toolbarToolClick({ code }) {
    // console.log(123, code, tool)
    switch (code) {
      case 'search':
        handelSearch()
        break
      case 'add':
        openForm('create')
        break
      case 'del':
        if (gridRef.value) {
          gridRef.value.commitProxy('delete')
        }
        break
    }
  }
}

const handelSearch = () => {
  searchRef.value?.open()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MailTemplateApi.deleteMailTemplate(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    const data = await MailTemplateApi.exportMailTemplate(queryParams)
    download.excel(data, '邮件模版.xls')
  } catch {
  } finally {
  }
}
</script>
